
#include "spi_bus.h"

static spi_client_t spi_client;
static uint64_t transfer_bytes = 0;
static uint8_t rx_buffer[1000];
static uint8_t tx_buffer[1000];

static void _spi_test(void *arg)
{
    uint32_t i;
    uint32_t magic;
    spi_msg_t msgs;
    spi_bus_config_t config = SPI_BUS_CONFIG_DEFAULT;
    
    magic = 0;
    config.clk_hz = 60*1000*1000;
    spi_client_init(&spi_client, "spi1", &config, "PB6");
    while(1)
    {
        magic++;
        for(i=0; i<sizeof(tx_buffer)/sizeof(tx_buffer[0]); i++) {
            tx_buffer[i] = (uint8_t)(magic + i);
        }
        
        msgs.cs_take = 1;
        msgs.cs_release = 1;
        msgs.length = sizeof(rx_buffer);
        msgs.recv_buf = rx_buffer;
        msgs.send_buf = tx_buffer;
        if(spi_client_transfer(&spi_client, &msgs, 1) != 1) {
            printf("transfer failed\r\n");
            continue;
        }
        
        for(i=0; i<sizeof(rx_buffer)/sizeof(rx_buffer[0]); i++) {
            if(tx_buffer[i] != rx_buffer[i]) {
                printf("check failed\r\n");
                break;
            }
        }
        transfer_bytes += sizeof(rx_buffer);
    }
}

static void _print_test(void *arg)
{
    uint32_t tick;
    
    tick = 0;
    while(1)
    {
        vTaskDelay(1000);
        tick++;
        printf("transfer_bytes %lfMB, speed %lfKB/s\r\n", transfer_bytes/1024.0/1024.0, (double)transfer_bytes/tick/1024.0);
    }
}

void spi_test(void)
{
    TaskHandle_t handle;
    portBASE_TYPE result;
    
    result = xTaskCreate(_spi_test,
                         "_spi_test",
                         1024,
                         NULL,
                         tskIDLE_PRIORITY + 2,
                         &handle );
    if(result != pdPASS) {
    	printf("create task failed\r\n");
    }
    
    result = xTaskCreate(_print_test,
                         "_print_test",
                         1024,
                         NULL,
                         tskIDLE_PRIORITY + 2,
                         &handle );
    if(result != pdPASS) {
    	printf("create task failed\r\n");
    }
}
